import React, { useState } from 'react';
import type { TableData } from '../types';
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import { ChevronDown, Maximize2 } from 'lucide-react';

function truncateTable(content: string): string {
  const lines = content.split('\n');
  const tableLines = lines.filter(line => line.trim().startsWith('|'));
  
  if (tableLines.length === 0) return content;

  const truncatedTable = tableLines
    .slice(0, 9) // 表头 + 8行
    .map(line => {
      const columns = line.split('|').slice(1, -1); // 去掉首尾的 |
      return '|' + columns.slice(0, 4).join('|') + '|'; // 前3列 + 1列省略号
    });

  // 添加省略号提示
  if (tableLines.length > 9) {
    truncatedTable.push('|...|...|...|...|');
  }

  // 替换原表格
  const tableStart = lines.indexOf(tableLines[0]);
  const tableEnd = lines.indexOf(tableLines[tableLines.length - 1]);
  
  return [
    ...lines.slice(0, tableStart),
    ...truncatedTable,
    ...lines.slice(tableEnd + 1)
  ].join('\n');
}

export function ResultCard({ data }: Props) {
  const [showFullTable, setShowFullTable] = useState(false);

  const truncatedContent = truncateTable(data.content);

  return (
    <div className="bg-white p-6 rounded-lg shadow-md flex flex-col">
      <h2 className="text-xl font-bold mb-4">{data.title}</h2>
      <div className="prose max-w-none overflow-hidden">
        <ReactMarkdown remarkPlugins={[remarkGfm]}>{truncatedContent}</ReactMarkdown>
      </div>
      
      <button 
        onClick={() => setShowFullTable(true)}
        className="mt-4 self-center text-blue-500 hover:text-blue-700 transition-colors flex items-center gap-2"
      >
        <Maximize2 className="w-5 h-5" />
        <span>查看完整表格</span>
      </button>

      
    </div>
  );
}
